package com.narsimha.crosstab.helper;

import com.gaurav.tree.ArrayListTree;
import com.gaurav.tree.NodeNotFoundException;
import com.google.visualization.datasource.datatable.DataTable;
import com.google.visualization.datasource.datatable.TableCell;
import com.google.visualization.datasource.datatable.TableRow;
import com.google.visualization.datasource.datatable.value.NumberValue;
import com.google.visualization.datasource.datatable.value.TextValue;
import com.narsimha.model.Dimension;
import com.narsimha.model.DimensionValue;

public class DataToDsHelper {
	public void convert(DataTable dt) throws NodeNotFoundException {
		ArrayListTree<DimensionValue> xTree = new ArrayListTree<DimensionValue>();
		DimensionValue xRoot = new DimensionValue();
		xRoot.setKey(-1);
		xRoot.setName("RootX");
		xTree.add(xRoot);
		ArrayListTree<DimensionValue> yTree = new ArrayListTree<DimensionValue>();
		DimensionValue yRoot = new DimensionValue();
		yRoot.setKey(-1);
		yRoot.setName("RootY");
		yTree.add(yRoot);
		
		for(TableRow i : dt.getRows()) {
			for(Dimension j : StateHelper.getInstance().getxDimensions())
				xRoot = addTreeNode(dt, i, j, xTree, xRoot);
			for(Dimension j : StateHelper.getInstance().getyDimensions())
				yRoot = addTreeNode(dt, i, j, yTree, yRoot);
		}
	}

	private DimensionValue addTreeNode(DataTable dt, TableRow i, Dimension j, ArrayListTree<DimensionValue> tree, DimensionValue root) throws NodeNotFoundException {
		TableCell dimensionNameCell = i.getCell(dt.getColumnIndex(j.getDimensionName()));
		TableCell dimensionKeyCell = i.getCell(dt.getColumnIndex(j.getDimensionKeyColumnName()));
		DimensionValue dimensionValue = new DimensionValue();
		dimensionValue.setKey((int) ((NumberValue)dimensionKeyCell.getValue()).getValue());
		dimensionValue.setName(((TextValue)dimensionNameCell.getValue()).getValue());
		tree.add(root, dimensionValue);
		return dimensionValue;
	}
}